/**
 * 全局错误处理和调试工具
 */

// 错误日志收集
const errorLog = []

// 捕获未处理的错误
window.addEventListener('error', (event) => {
  // 过滤掉无害的ResizeObserver错误
  if (event.message && event.message.includes('ResizeObserver loop completed with undelivered notifications')) {
    event.preventDefault()
    return
  }

  const error = {
    type: 'JavaScript Error',
    message: event.message,
    filename: event.filename,
    lineno: event.lineno,
    colno: event.colno,
    stack: event.error?.stack,
    timestamp: new Date().toISOString(),
    url: window.location.href
  }

  errorLog.push(error)
  console.error('应用错误:', error.message)

  // 不在页面上显示错误信息，只记录到控制台
  // displayError(error)
})

// 捕获未处理的Promise rejection
window.addEventListener('unhandledrejection', (event) => {
  const error = {
    type: 'Unhandled Promise Rejection',
    message: event.reason?.message || event.reason,
    stack: event.reason?.stack,
    timestamp: new Date().toISOString(),
    url: window.location.href
  }

  errorLog.push(error)
  console.error('Promise错误:', error.message)

  event.preventDefault()
  // 不在页面上显示错误信息，只记录到控制台
  // displayError(error)
})

// 显示错误信息到页面
function displayError(error) {
  const errorDisplay = document.getElementById('error-display')
  if (errorDisplay) {
    errorDisplay.innerHTML += `
      <div style="background: #ffebee; border: 1px solid #f44336; color: #d32f2f;
                  padding: 10px; margin: 5px 0; border-radius: 4px; font-family: monospace;">
        <strong>[${error.timestamp}]</strong> ${error.type}<br>
        <strong>错误:</strong> ${error.message}<br>
        ${error.filename ? `<strong>文件:</strong> ${error.filename}:${error.lineno}<br>` : ''}
        ${error.stack ? `<strong>堆栈:</strong><pre>${error.stack}</pre>` : ''}
      </div>
    `
  }
}

// 创建错误显示区域
function createErrorDisplay() {
  const errorDiv = document.createElement('div')
  errorDiv.id = 'error-display'
  errorDiv.style.cssText = `
    position: fixed;
    top: 10px;
    right: 10px;
    width: 400px;
    max-height: 300px;
    overflow-y: auto;
    background: white;
    border: 2px solid #f44336;
    border-radius: 8px;
    padding: 10px;
    z-index: 9999;
    font-size: 12px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
  `

  const closeBtn = document.createElement('button')
  closeBtn.textContent = '×'
  closeBtn.style.cssText = `
    position: absolute;
    top: 5px;
    right: 5px;
    background: #f44336;
    color: white;
    border: none;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    cursor: pointer;
  `
  closeBtn.onclick = () => errorDiv.style.display = 'none'

  const title = document.createElement('div')
  title.textContent = '错误信息'
  title.style.cssText = `
    font-weight: bold;
    margin-bottom: 10px;
    color: #d32f2f;
  `

  errorDiv.appendChild(closeBtn)
  errorDiv.appendChild(title)
  document.body.appendChild(errorDiv)

  return errorDiv
}

// 简化的调试工具
export const debug = {
  // 获取错误日志
  getErrorLog: () => {
    return [...errorLog]
  },

  // 清除错误日志
  clearErrorLog: () => {
    errorLog.length = 0
    const errorDisplay = document.getElementById('error-display')
    if (errorDisplay) {
      errorDisplay.innerHTML = '<div style="font-weight: bold; margin-bottom: 10px;">错误信息</div>'
    }
  }
}

// 不创建错误显示区域，只在控制台记录错误
// if (document.readyState === 'loading') {
//   document.addEventListener('DOMContentLoaded', createErrorDisplay)
// } else {
//   createErrorDisplay()
// }

// 导出错误日志用于外部访问
window.errorLog = errorLog
window.debug = debug